import { Controller, Get, Post, Body, Patch, Param, Delete, Inject, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { JwtService } from '@nestjs/jwt';
import { JwtAuthGuard } from '../jwt.auth.guard'

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) { }

  //登录
  // @Post('/login')
  // login(@Body() createUserDto: CreateUserDto) {
  //   return this.userService.login(createUserDto)
  // }
  @Inject(JwtService)
  private jwtService: JwtService

  @Post('/login')
  async login(@Body() params: CreateUserDto) {
    const foundUser = await this.userService.login(params)
    const access_token = this.jwtService.sign({
      user: {
        username: foundUser.username,
        sub: foundUser.id,
      },
    });
    // console.log(access_token);
    if (foundUser) {
      return {
        username: foundUser.username,
        access_token: 'Bearer ' + access_token,
      }
    }
  }

  //添加
  @Post('/add')
  @UseGuards(JwtAuthGuard)
  create(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }

  @Get('/user')
  findAll() {
    return this.userService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.userService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(+id, updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(+id);
  }
}
